﻿using BCC.Comcon;
using BCC.Common;
using BCC.Common.Common;
using BCC.Communication.SocketClient;
using BCC.MainLeft;
using BCC.Model.chat;
using BCC.Model.Enumeration;
using BCC.Model.Monitor;
using BCC.Model.user;
using BCC.VB.ViewCommunication;
using BCC.ViewModel.chat;
using BCC.ViewModel.user;
using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;


namespace BCC
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private BCCUser bccUser = new BCCUser();
        BCC.Communication.SocketClient.client client;

        public MainWindow(BCCUser _bCCUser, client _client)
        {
            InitializeComponent();

            bccUser = _bCCUser;
            client = _client;

            #region 左边
            var unreadChats = GetAllUnreadChat(bccUser.Account);

            if (unreadChats!=null&&unreadChats.Any())
            {
                var unreadChatGroup = unreadChats.GroupBy(u => u.SendAccount).ToList();
                var row = 0;
                foreach (var item in unreadChatGroup)
                {
                    LeftFriends leftFriends = new LeftFriends(item.ToList());
                    AddLeftFriends(leftFriends, item.FirstOrDefault().SendAccount, row);
                    row++;
                }
            }

            #endregion

            #region 中间
            StackPanelInfoLoaded();
            Monitor.PartEvent += OnStep;//将该类中的函数注册到Monitor静态类的PartEvent事件中。
            Monitor.PartPicEvent += OnPicStep;//将该类中的函数注册到Monitor静态类的PartEvent事件中。
            #endregion

            #region 富文本

            //sendRichTextBox.PreviewKeyDown += (sender, e) =>
            //{
            //    if (e.Key == Key.V && Keyboard.Modifiers == ModifierKeys.Control)
            //    {
            //        DataObject dataObject = new DataObject();
            //        Clipboard.SetDataObject(dataObject);
            //        sendRichTextBox.Paste();
            //        e.Handled = true;
            //    }
            //};

            //sendRichTextBox.AddHandler(DataObject.PastingEvent, new DataObjectPastingEventHandler((sender, e) =>
            //{
            //    if (e.SourceDataObject.GetDataPresent(DataFormats.Bitmap))
            //    {
            //        BitmapSource image = e.SourceDataObject.GetData(DataFormats.Bitmap) as BitmapSource;
            //        var block = new BlockUIContainer(new Image() { Source = image });
            //        sendRichTextBox.Document.Blocks.Add(block);
            //        e.CancelCommand();
            //    }
            //}), true);

            #endregion
        }

        public void OnStep(Object sender, MessageArgs message)
        {

            Application.Current.Dispatcher.Invoke(new Action(() =>
            {
                AddReceivedUserControl(new UserControlMessageReceived(), message.TxtMessage, message.TxtTime);
            }));
        }

        //接收图片
        public void OnPicStep(Object sender, MessagePicArgs message)
        {

            Application.Current.Dispatcher.Invoke(new Action(() =>
            {
                AddReceivedPicUserControl(new UserControlMessageReceived(), message.imgMessage, message.TxtTime, message.imageType);
            }));
        }

        private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            DragMove();
        }

        private void Close_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        #region 中间
        private void StackPanelInfo_Loaded(object sender, RoutedEventArgs e)
        {
            var sendAccount = bccUser.Account;//发送人账号

            var receiveAccount = Account.Text;
            var info = Getchat.selChatinfo(sendAccount, receiveAccount);

            if (info.Any())
            {
                foreach (var item in info)
                {
                    if (item.SendAccount == sendAccount)
                    {
                        UserControlMessageSent sent = new UserControlMessageSent();

                        AddSentUserControl(sent, item.Info, TimeHelper.getTimeHHmmss(item.CreateTime));
                    }
                    else if (item.ReceiveAccount == sendAccount)
                    {
                        UserControlMessageReceived received = new UserControlMessageReceived();
                        AddReceivedUserControl(received, item.Info, TimeHelper.getTimeHHmmss(item.CreateTime));
                    }
                }
            }
        }

        private void StackPanelInfoLoaded()
        {
            var sendAccount = bccUser.Account;//发送人账号

            var receiveAccount = Account.Text;
            var info = Getchat.selChatinfo(sendAccount, receiveAccount);

            if (info.Any())
            {
                foreach (var item in info)
                {
                    if (item.SendAccount == sendAccount)
                    {
                        UserControlMessageSent sent = new UserControlMessageSent();

                        AddSentUserControl(sent, item.Info, TimeHelper.getTimeHHmmss(item.CreateTime));
                    }
                    else if (item.ReceiveAccount == sendAccount)
                    {
                        UserControlMessageReceived received = new UserControlMessageReceived();
                        AddReceivedUserControl(received, item.Info, TimeHelper.getTimeHHmmss(item.CreateTime));
                    }
                }
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            #region 图片 弃用
            //TextRange sendTextBox = new TextRange(sendRichTextBox.Document.ContentStart, sendRichTextBox.Document.ContentEnd);
            ////var a= sendTextBox.;

            ////IEnumerable<Inline> inlines = sendRichTextBox.Document.Blocks.Select(x => x.Inlines);


            //var blocks = sendRichTextBox.Document.Blocks;
            //var inlines = GetAllInlines(blocks);

            //// 将所有Inline元素转换为字节数组
            //List<byte[]> data = new List<byte[]>();
            //foreach (Inline inline in inlines)
            //{
            //    if (inline is Run)
            //    {
            //        // 处理文本Run元素
            //        string text = (inline as Run).Text;
            //        byte[] textBytes = Encoding.UTF8.GetBytes(text);
            //        data.Add(textBytes);
            //    }
            //    else if (inline is InlineUIContainer)
            //    {
            //        // 处理图像InlineUIContainer元素
            //        InlineUIContainer container = inline as InlineUIContainer;
            //        Image image = container.Child as Image;

            //        BitmapSource bitmapSource = image.Source as BitmapSource;
            //        JpegBitmapEncoder encoder = new JpegBitmapEncoder();
            //        encoder.Frames.Add(BitmapFrame.Create(bitmapSource));

            //        using (MemoryStream ms = new MemoryStream())
            //        {
            //            encoder.Save(ms);
            //            data.Add(ms.ToArray());
            //        }
            //    }
            //}
            #endregion

            //发起socket通讯
            client.sendStrMes(sendTextBox.Text, Account.Text);
            //client.SendPicAndStringMes(sendTextBox.Text, Account.Text);
            
            //往指定文件保存数据  数据库添加值 

            //修改页面
            AddSentUserControl(new UserControlMessageSent(), sendTextBox.Text, TimeHelper.getTimeHHmmss());
        }



        /// <summary>
        /// 添加发送消息框
        /// </summary>
        /// <param name="sent"></param>
        /// <param name="text"></param>
        /// <param name="time"></param>
        public void AddSentUserControl(UserControlMessageSent sent, string text, string time)
        {
            sent.HorizontalAlignment = HorizontalAlignment.Right;

            var sendText = (TextBlock)sent.FindName("SendText");
            sendText.Text = text;

            var sendTime = (TextBlock)sent.FindName("SendTime");
            sendTime.Text = time;

            StackPanelInfo.Children.Add(sent);
        }

        /// <summary>
        /// 添加接收消息框
        /// </summary>
        /// <param name="received"></param>
        /// <param name="text"></param>
        /// <param name="time"></param>
        public void AddReceivedUserControl(UserControlMessageReceived received, string text, string time)
        {
            received.HorizontalAlignment = HorizontalAlignment.Left;

            var receivedText = (TextBlock)received.FindName("ReceiveText");
            receivedText.Text = text;

            var receivedTime = (TextBlock)received.FindName("ReceiveTime");
            receivedTime.Text = time;

            StackPanelInfo.Children.Add(received);
        }

        /// <summary>
        /// 添加接收消息框(图片)
        /// </summary>
        /// <param name="received"></param>
        /// <param name="text"></param>
        /// <param name="time"></param>
        public void AddReceivedPicUserControl(UserControlMessageReceived received, byte[] imgbyte, string time, ImageType imageType)
        {
            var img = Utils.BytesToImage(imgbyte);
            received.HorizontalAlignment = HorizontalAlignment.Left;

            var receivedText = (Border)received.FindName("ReceiveBorder");

            BitmapImage bitmapImage = new BitmapImage();
            MemoryStream memoryStream = new MemoryStream();


            ImageFormat format = ImageFormat.Png;
            format = Utils.SaveImage(imageType);
            img.Save(memoryStream, format);

            memoryStream.Position = 0;
            bitmapImage.BeginInit();
            bitmapImage.StreamSource = memoryStream;
            bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
            bitmapImage.EndInit();

            ImageBrush brush = new ImageBrush();
            brush.ImageSource = bitmapImage; // yourImage是已加载到内存中的Image对象
            receivedText.Background = brush;

            var receivedTime = (TextBlock)received.FindName("ReceiveTime");
            receivedTime.Text = time;

            StackPanelInfo.Children.Add(received);
        }

        #endregion

        #region 左侧
        /// <summary>
        /// 添加左侧好友
        /// </summary>
        /// <param name="leftFriends"></param>
        /// <param name="account"></param>
        /// <param name="row"></param>
        public void AddLeftFriends(LeftFriends leftFriends, string account, int row)
        {
            if (row == 0)
            {
                var userinfo = Getuser.selUserInfo(account);
                SetChatInfo(userinfo);
            }
            leftFriends.Name = "Name"+account.ToString();
            leftFriends.SetValue(Grid.RowProperty, row);
            LeftGrid.Children.Add(leftFriends);
        }

        public List<UChatinfo> GetAllUnreadChat(string account)
        {
            return Getchat.selChatAllUnreadinfo(account);
        }
        #endregion

        #region 右侧 和 中间头部
        public void SetChatInfo(BCCUser account)
        {
            if (account!=null)
            {
                chatUserName.Text = UserName.Text = account.UserName;
                Account.Text = account.Account;
                UserSign.Text = account.UserSign;
                Address.Text = account.Address;
                Telephone.Text = account.Telephone;
                Mail.Text = account.Mail;
            }
        }
        #endregion


        #region common
        private IEnumerable<Inline> GetAllInlines(IEnumerable<Block> blocks)
        {
            foreach (var block in blocks)
            {
                if (block is Paragraph paragraph)
                {
                    foreach (var inline in paragraph.Inlines)
                    {
                        yield return inline;
                    }
                }
                else if (block is Section section)
                {
                    foreach (var inline in GetAllInlines(section.Blocks))
                    {
                        yield return inline;
                    }
                }
                else if (block is List list)
                {
                    foreach (var item in list.ListItems)
                    {
                        foreach (var inline in GetAllInlines(item.Blocks))
                        {
                            yield return inline;
                        }
                    }
                }
                // Add more block types here as needed...
            }
        }
        #endregion
    }
}
